import os
from datetime import datetime

from docx import Document
from flask import request, render_template, send_file
import re
import logging

from pptx import Presentation

# file_path_root = "H:\\"  # windows环境使用


file_path_root = "/home/will"  # Linux环境使用


# file_path_root = "/home/will" # linux环境使用
def upload_files():
    # 获取上传的两个文件
    file1 = request.files['file1']
    file2 = request.files['file2']

    # 保存上传的文件
    file1Path = file_path_root + file1.filename
    file2Path = file_path_root + file2.filename
    file1.save(file1Path)
    file2.save(file2Path)

    # 合并两个文件
    return add_word_to_ppt_notes(file1, file2)

    # # 返回合并后的文件给用户下载
    # return send_file(merged_file, as_attachment=True)


def add_word_to_ppt_notes(file1, file2):
    # 打开 Word 文档
    doc = Document(file1)

    # 打开现有的 PPT 文档
    prs = Presentation(file2)

    current_slide_index = -1
    current_content = []

    # 遍历 Word 文档中的每个段落
    for paragraph in doc.paragraphs:
        if paragraph.style.name.startswith('Heading 1'):
            if current_slide_index < len(prs.slides):
                # 将之前收集的正文内容添加到幻灯片的备注中
                add_content_to_slide(current_content, prs.slides[current_slide_index])
                current_slide_index += 1
            current_content = []  # 清空正文内容
        else:
            current_content.append(paragraph.text)  # 收集正文内容

    # 处理最后一页的正文内容
    if current_slide_index < len(prs.slides):
        add_content_to_slide(current_content, prs.slides[current_slide_index])

    # merge_file_name = os.path.splitext(file1)[0] + "_" + os.path.splitext(file2)[0] + "_" + datetime.now().strftime('%Y%m%d%H%M%S') + ".pptx"
    # merged_file = os.path.join(os.path.dirname(__file__), merge_file_name)

    merge_file_name = file1.filename.split(".")[0] + "_" + file2.filename.split(".")[0]+ datetime.now().strftime('%Y%m%d%H%M%S') + ".pptx"
    merged_file = file_path_root + merge_file_name

    # 保存修改后的 PPT 文档
    prs.save(merged_file)
    return merge_file_name


def add_content_to_slide(content, slide):
    notes_slide = slide.notes_slide
    notes_shape = notes_slide.notes_text_frame

    notes_shape.text = '\n'.join(content)